package com.ggy.babybed.socketwork.command;

import com.ggy.babybed.socketwork.NetworkConstant;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author gonggy
 *
 */
public class BaseCommand implements INetworkCommand {

    /**
     * 读取一行
     * @param in
     * @return
     * @throws IOException
     */
    protected String readLine(InputStream in) throws IOException{
        byte preRead = 0;
        byte nowRead;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        nowRead = (byte) in.read();
        if(-1 == nowRead){
            throw new IOException("没有可读的数据");
        } else {
            bos.write(nowRead);
            while(true){
                nowRead = (byte) in.read();
                if(-1 == nowRead){
                    break;
                }
                bos.write(nowRead);
                if(preRead == '\r' && nowRead == '\n'){
                    break;
                }
                preRead = nowRead;
            }
        }
        String line = bos.toString(NetworkConstant.DEFAULT_ENCODING);
        return line.trim();
    }

    /**
     * 获取字符输出流，默认字符编码为UTF-8
     * @param out
     * @return
     * @throws UnsupportedEncodingException
     */
    protected OutputStreamWriter getStringWriter(OutputStream out) throws UnsupportedEncodingException{
        return new OutputStreamWriter(out, NetworkConstant.DEFAULT_ENCODING);
    }

    protected String[] getSplitArray(String str){
        if(null == str || "".equals(str)){
            return new String[]{};
        }
        return str.split(NetworkConstant.SEPARATOR);
    }

    @Override
    public boolean write(OutputStream outStream) throws IOException {
        return false;
    }

    @Override
    public boolean read(InputStream inStream) throws IOException {
        return false;
    }

}
